package link.cocoon.common.redis;

import java.util.concurrent.TimeUnit;
import javax.annotation.Resource;
import link.cocoon.common.cache.ICache;
import link.cocoon.common.global.config.ProjectConstantConfig;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

/**
 * @author xce
 * @date 2020/3/19  10:26
 */
@Service
public abstract class RedisCache<V> implements ICache<V> {

  @Override
  public long getMaxTimeout() {
    return 3600;
  }

  @Override
  public TimeUnit getTimeUnit() {
    return TimeUnit.SECONDS;
  }

  @Resource
  private RedisTemplate<String, V> redisTemplate;

  @Resource
  private ProjectConstantConfig projectConstantConfig;

  protected String initKey(String key) {
    String projectName = projectConstantConfig.getName();
    return projectName + ":" + getModuleName() + ":" + key;
  }

  protected String initKey(String key, String param) {
    return initKey(key) + ":" + param;
  }


  protected abstract String getModuleName();

  @Override
  public V get(String key) {
    return redisTemplate.opsForValue().get(initKey(key));

  }

  @Override
  public V get(String key, String param) {
    return redisTemplate.opsForValue().get(initKey(key, param));
  }

  @Override
  public void put(String key, V value) {
    redisTemplate.opsForValue().set(initKey(key), value, getMaxTimeout(), getTimeUnit());
  }

  @Override
  public void put(String key, String param, V value) {
    redisTemplate.opsForValue().set(initKey(key, param), value, getMaxTimeout(), getTimeUnit());
  }

  @Override
  public void put(String key, V value, long timeout) {
    redisTemplate.opsForValue().set(key, value, timeout, getTimeUnit());
  }

  @Override
  public boolean exit(String key) {
    Boolean hasKey = redisTemplate.hasKey(initKey(key));
    return (hasKey != null) && hasKey;
  }

  @Override
  public boolean exit(String key, String param) {
    Boolean hasKey = redisTemplate.hasKey(initKey(key, param));
    return (hasKey != null) && hasKey;
  }
}
